package com.wjpeng.wms.interceptor;

import com.wjpeng.wms.domain.Employee;
import com.wjpeng.wms.domain.Permission;
import com.wjpeng.wms.util.PermissionUtil;
import com.wjpeng.wms.util.RequiredPermission;
import com.wjpeng.wms.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

//权限检查拦截器
public class SecurityInterceptor extends HandlerInterceptorAdapter{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //取出当前登陆的用户
        Employee employee = UserContext.getCurrentUser();

        //超级管理员,放行
        if (employee.getAdmin()) {
            return true;
        }

        //当前访问的方法是否需要权限
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();//得到请求目标方法

        //判断当前方法是否需要权限
        if(!method.isAnnotationPresent(RequiredPermission.class)){
            //当前方法不要权限,放行
            return true;
        }

        //当前方法需要权限,当前用户是否拥有该权限
        List<String> expressions = UserContext.getExpression();
        String expression = PermissionUtil.buildEmpression(method);
        if (expressions.contains(expression)) {
            //当前用户有权限,放行
            return true;

        }

        throw new SecurityException();

    }
}
